<?php
session_start();

// 函数：检查并初始化文件
function ensureFile($filename, $defaultContent = '[]') {
    if (!file_exists($filename)) {
        file_put_contents($filename, $defaultContent);
    }
    $content = file_get_contents($filename);
    $data = json_decode($content, true);
    return is_array($data) ? $data : json_decode($defaultContent, true);
}

// 加载用户文件
$users = ensureFile('users.json');
$currentUser = $_SESSION['username'] ?? null;

if (!$currentUser) {
    header('Location: login.php');
    exit();
}

// 加载好友关系文件
$friends = ensureFile('friends.json');
$friendRequests = ensureFile('messages/system_messages.json');

$searchResults = [];
$notification = ['type' => '', 'message' => ''];

// 检查两个用户是否已经是好友
function isFriend($user1, $user2, $friends) {
    foreach ($friends as $friend) {
        if (($friend['user1'] === $user1 && $friend['user2'] === $user2) ||
            ($friend['user1'] === $user2 && $friend['user2'] === $user1)) {
            return true;
        }
    }
    return false;
}

// 检查是否已存在好友请求（当前用户发出或接收的）
function hasExistingRequest($currentUser, $targetUser, $requests) {
    foreach ($requests as $request) {
        if ($request['type'] === 'friend_request') {
            $isFromCurrent = ($request['from_user'] === $currentUser && $request['to_user'] === $targetUser);
            $isToCurrent = ($request['from_user'] === $targetUser && $request['to_user'] === $currentUser);
            
            if ($isFromCurrent || $isToCurrent) {
                return true;
            }
        }
    }
    return false;
}

// 处理搜索逻辑 - 仅使用用户名搜索
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['search_query'])) {
    $searchQuery = trim($_POST['search_query']);
    if (empty($searchQuery)) {
        $notification = ['type' => 'error', 'message' => '请输入用户名进行搜索'];
    } else {
        foreach ($users as $user) {
            $targetUsername = $user['username'];
            
            // 排除自己和已经是好友的用户
            if (stripos($targetUsername, $searchQuery) !== false && 
                $targetUsername !== $currentUser) {
                
                // 检查是否已经是好友
                $alreadyFriends = isFriend($currentUser, $targetUsername, $friends);
                
                // 检查是否已存在待处理的好友请求（任何方向）
                $hasExisting = hasExistingRequest($currentUser, $targetUsername, $friendRequests);
                
                // 只有当不是好友且没有现存请求时才显示
                if (!$alreadyFriends && !$hasExisting) {
                    $searchResults[] = [
                        'username' => $targetUsername
                    ];
                }
            }
        }
        if (empty($searchResults)) {
            $notification = ['type' => 'error', 'message' => '未找到相关用户，或该用户已是好友/已有请求'];
        }
    }
}

// 处理好友请求逻辑
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['to_user'])) {
    $toUser = trim($_POST['to_user']);
    $messagesFile = 'messages/system_messages.json';
    $messages = ensureFile($messagesFile);

    // 0. 检查是否是给自己发送请求
    if ($toUser === $currentUser) {
        $notification = ['type' => 'error', 'message' => '不能添加自己为好友'];
    }
    // 1. 检查是否已经是好友
    elseif (isFriend($currentUser, $toUser, $friends)) {
        $notification = ['type' => 'error', 'message' => '你们已经是好友，无法重复添加'];
    } 
    // 2. 检查是否已存在好友请求（包括对方发给你的）
    elseif (hasExistingRequest($currentUser, $toUser, $messages)) {
        $notification = ['type' => 'error', 'message' => '已存在好友请求'];
    } else {
        // 发送好友请求
        $messages[] = [
            'type' => 'friend_request',
            'from_user' => $currentUser,
            'to_user' => $toUser,
            'status' => 'pending',
            'timestamp' => date('Y-m-d H:i:s')
        ];
        file_put_contents($messagesFile, json_encode($messages, JSON_PRETTY_PRINT));
        $notification = ['type' => 'success', 'message' => '好友请求已发送'];
    }
}
?>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>添加好友 - JIIL微聊</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
        }
        
        body {
            background-color: #f8f9fa;
            color: #333;
            line-height: 1.5;
            min-height: 100vh;
        }
        
        .top-bar {
            background: white;
            padding: 16px 20px;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
            display: flex;
            align-items: center;
            position: sticky;
            top: 0;
            z-index: 100;
        }
        
        .back-btn {
            background: none;
            border: none;
            color: #000;
            font-size: 20px;
            margin-right: 15px;
            cursor: pointer;
            width: 36px;
            height: 36px;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            transition: all 0.3s ease;
        }
        
        .back-btn:hover {
            background: #f0f2f5;
        }
        
        .page-title {
            font-size: 20px;
            font-weight: 600;
            color: #333;
            flex-grow: 1;
            text-align: center;
        }
        
        .container {
            max-width: 600px;
            margin: 0 auto;
            padding: 30px 20px;
        }
        
        .search-card {
            background: white;
            border-radius: 16px;
            padding: 30px;
            box-shadow: 0 5px 20px rgba(0, 0, 0, 0.05);
            margin-bottom: 25px;
        }
        
        .search-header {
            text-align: center;
            margin-bottom: 25px;
        }
        
        .search-header h2 {
            font-size: 24px;
            color: #333;
            margin-bottom: 10px;
        }
        
        .search-header p {
            color: #666;
            max-width: 500px;
            margin: 0 auto;
            font-size: 15px;
            line-height: 1.6;
        }
        
        .search-form {
            display: flex;
            gap: 12px;
            margin-bottom: 20px;
        }
        
        .search-input {
            flex: 1;
            padding: 16px 20px;
            border: 1px solid #e0e4e9;
            border-radius: 12px;
            font-size: 16px;
            transition: all 0.3s ease;
        }
        
        .search-input:focus {
            border-color: #3b82f6;
            outline: none;
            box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.15);
        }
        
        .search-btn {
            background: #3b82f6;
            color: white;
            border: none;
            border-radius: 12px;
            padding: 0 30px;
            font-size: 16px;
            font-weight: 500;
            cursor: pointer;
            transition: all 0.3s ease;
            display: flex;
            align-items: center;
            gap: 8px;
        }
        
        .search-btn:hover {
            background: #2563eb;
        }
        
        .notification {
            padding: 15px 20px;
            border-radius: 12px;
            font-size: 15px;
            font-weight: 500;
            margin-bottom: 20px;
            display: flex;
            align-items: center;
            gap: 12px;
            animation: fadeIn 0.3s;
        }
        
        .notification.error {
            background: #fef2f2;
            color: #ef4444;
            border: 1px solid #fee2e2;
        }
        
        .notification.success {
            background: #f0fdf4;
            color: #22c55e;
            border: 1px solid #dcfce7;
        }
        
        @keyframes fadeIn {
            from { opacity: 0; transform: translateY(-10px); }
            to { opacity: 1; transform: translateY(0); }
        }
        
        .results-container {
            display: flex;
            flex-direction: column;
            gap: 15px;
        }
        
        .user-card {
            background: white;
            border-radius: 15px;
            padding: 20px;
            display: flex;
            align-items: center;
            justify-content: space-between;
            box-shadow: 0 3px 10px rgba(0, 0, 0, 0.05);
            transition: all 0.3s ease;
            border: 1px solid #f0f2f5;
        }
        
        .user-card:hover {
            transform: translateY(-3px);
            box-shadow: 0 6px 15px rgba(0, 0, 0, 0.08);
            border-color: #e5e7eb;
        }
        
        .user-info {
            flex: 1;
        }
        
        .user-info h3 {
            font-size: 18px;
            margin-bottom: 5px;
            color: #333;
            font-weight: 600;
        }
        
        .actions {
            display: flex;
            gap: 12px;
        }
        
        .btn {
            padding: 10px 16px;
            border-radius: 10px;
            font-weight: 500;
            font-size: 14px;
            cursor: pointer;
            transition: all 0.3s ease;
            border: none;
            display: flex;
            align-items: center;
            gap: 6px;
        }
        
        .add-btn {
            background: #3b82f6;
            color: white;
        }
        
        .add-btn:hover {
            background: #2563eb;
        }
        
        .add-btn.pending {
            background: #e5e7eb;
            color: #6b7280;
            cursor: not-allowed;
        }
        
        .profile-btn {
            background: #f5f5f5;
            color: #333;
        }
        
        .profile-btn:hover {
            background: #e5e7eb;
        }
        
        .btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 3px 8px rgba(0, 0, 0, 0.08);
        }
        
        .empty-state {
            text-align: center;
            padding: 50px 20px;
            color: #9ca3af;
        }
        
        .empty-icon {
            font-size: 48px;
            margin-bottom: 15px;
            color: #d1d5db;
        }
        
        .empty-title {
            font-size: 18px;
            font-weight: 600;
            margin-bottom: 8px;
            color: #6b7280;
        }
        
        .empty-text {
            max-width: 400px;
            margin: 0 auto;
            font-size: 14px;
            line-height: 1.6;
        }
        
        @media (max-width: 768px) {
            .container {
                padding: 20px 15px;
            }
            
            .search-card {
                padding: 25px;
            }
            
            .search-form {
                flex-direction: column;
            }
            
            .search-btn {
                padding: 16px;
                justify-content: center;
            }
            
            .user-card {
                flex-direction: column;
                text-align: center;
                gap: 15px;
            }
            
            .actions {
                width: 100%;
                justify-content: center;
            }
        }
    </style>
</head>
<body>
    <div class="top-bar">
        <button class="back-btn" onclick="history.back()">
            <i class="fas fa-arrow-left"></i>
        </button>
        <div class="page-title">添加好友</div>
    </div>
    
    <div class="container">
        <div class="search-card">
            <div class="search-header">
                <h2>搜索添加好友</h2>
                <p>通过用户名搜索好友，添加后可以开始聊天并分享动态</p>
            </div>
            
            <?php if (!empty($notification['message'])): ?>
                <div class="notification <?= $notification['type'] ?>">
                    <i class="fas <?= $notification['type'] === 'success' ? 'fa-check-circle' : 'fa-exclamation-triangle' ?>"></i>
                    <span><?= $notification['message'] ?></span>
                </div>
            <?php endif; ?>
            
            <form method="POST" class="search-form" id="searchForm">
                <input 
                    type="text" 
                    id="search_query" 
                    name="search_query" 
                    required 
                    placeholder="输入用户名进行搜索" 
                    class="search-input"
                    autocomplete="off"
                    value="<?= htmlspecialchars($_POST['search_query'] ?? '') ?>"
                >
                <button type="submit" class="search-btn">
                    <i class="fas fa-search"></i> 搜索
                </button>
            </form>
            
            <div class="results-container">
                <?php if (isset($_POST['search_query'])): ?>
                    <?php if (!empty($searchResults)): ?>
                        <?php foreach ($searchResults as $result): ?>
                            <div class="user-card">
                                <div class="user-info">
                                    <h3><?= htmlspecialchars($result['username']) ?></h3>
                                </div>
                                <div class="actions">
                                    <form method="POST" class="action-form">
                                        <input type="hidden" name="to_user" value="<?= htmlspecialchars($result['username']) ?>">
                                        <button type="submit" class="btn add-btn">
                                            <i class="fas fa-user-plus"></i> 添加好友
                                        </button>
                                    </form>
                                    <a 
                                        href="seauser.php?q=<?= urlencode($result['username']) ?>" 
                                        class="btn profile-btn"
                                    >
                                        <i class="fas fa-user"></i> 资料
                                    </a>
                                </div>
                            </div>
                        <?php endforeach; ?>
                    <?php else: ?>
                        <div class="empty-state">
                            <div class="empty-icon">
                                <i class="fas fa-user-slash"></i>
                            </div>
                            <div class="empty-title">未找到匹配的用户</div>
                            <div class="empty-text">
                                没有找到匹配的用户名，或该用户已经是您的好友/已有请求
                            </div>
                        </div>
                    <?php endif; ?>
                <?php else: ?>
                    <div class="empty-state">
                        <div class="empty-icon">
                            <i class="fas fa-search"></i>
                        </div>
                        <div class="empty-title">搜索添加好友</div>
                        <div class="empty-text">
                            在搜索框中输入用户名，查找并添加好友
                        </div>
                    </div>
                <?php endif; ?>
            </div>
        </div>
    </div>
    
    <script>
        // 表单提交验证
        document.getElementById('searchForm').addEventListener('submit', function(e) {
            const searchInput = document.getElementById('search_query');
            if (searchInput.value.trim() === '') {
                e.preventDefault();
                const errorElement = document.createElement('div');
                errorElement.className = 'notification error';
                errorElement.innerHTML = `
                    <i class="fas fa-exclamation-triangle"></i>
                    <span>请输入用户名</span>
                `;
                this.parentNode.insertBefore(errorElement, this.nextSibling);
                setTimeout(() => errorElement.remove(), 4000);
            }
        });
        
        // 添加好友按钮动画
        document.querySelectorAll('.add-btn').forEach(btn => {
            btn.addEventListener('click', function() {
                const originalHTML = this.innerHTML;
                this.innerHTML = '<i class="fas fa-spinner fa-spin"></i> 发送中...';
                this.disabled = true;
                this.closest('form').submit();
            });
        });
        
        // 自动聚焦搜索框
        document.addEventListener('DOMContentLoaded', function() {
            const searchInput = document.getElementById('search_query');
            searchInput && searchInput.focus();
        });
    </script>
</body>
</html>